import axios from 'axios'
import { hideLoading, showLoading } from './loading'
import type { IResult } from '@/types/commonType'
import { message } from './AntdGlobal'
import storage from './storage'

// 创建实例
const instance = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 8000
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = storage.get('token')
    if (token) config.headers.Authorization = 'Bearer ' + token
    if (config.showLoading) showLoading()
    return config
  },
  error => {
    hideLoading()
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  response => {
    if (response.config.showLoading) hideLoading()
    if (response.config.responseType == 'blob') return response
    const data: IResult = response.data
    // 登录失效
    if (data.code === 500001) {
      if (response.config.showError) message.error(data.msg)
      storage.remove('token')
      location.href = `/login?callback=${location.href}`
      return Promise.reject(data)
    }
    // 访问失败
    if (data.code != 0) {
      if (response.config.showError) message.error(data.msg)
      return Promise.reject(data)
    }
    return data.data
  },
  error => {
    hideLoading()
    return Promise.reject(error)
  }
)

interface IConfig {
  showLoading?: boolean
  showError?: boolean
}

export default {
  get<T>(url: string, params?: object, options: IConfig = { showError: true, showLoading: true }): Promise<T> {
    return instance.get(url, { params, ...options })
  },
  post<T>(url: string, params?: object, options: IConfig = { showError: true, showLoading: true }): Promise<T> {
    return instance.post(url, params, options)
  },
  downLoad(url: string, data: any) {
    instance({
      url,
      data,
      method: 'post',
      responseType: 'blob'
    }).then(res => {
      console.log(res)
      const blob = new Blob([res.data], { type: res.data.type })
      const name = res.headers['file-name']
      const link = document.createElement('a')
      link.download = decodeURIComponent(name)
      link.href = window.URL.createObjectURL(blob)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(link.href)
    })
  }
}
